# Logging configuration module
import logging
import logging.handlers
import os
from datetime import datetime
import json

class DatabaseQueryLogger:
    """Database query logger"""
    
    def __init__(self):
        self.logger = logging.getLogger('database_queries')
        self.logger.setLevel(logging.INFO)
        
        # Create log directory
        log_dir = 'logs'
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        
        # File handler - rotate by date
        file_handler = logging.handlers.TimedRotatingFileHandler(
            filename=os.path.join(log_dir, 'database_queries.log'),
            when='midnight',
            interval=1,
            backupCount=30,
            encoding='utf-8'
        )
        
        # Console handler
        console_handler = logging.StreamHandler()
        
        # Set format
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # Add handlers
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
    
    def log_query(self, query, params=None, execution_time=None, user_id=None, success=True):
        """Log database query"""
        log_data = {
            'timestamp': datetime.now().isoformat(),
            'query': query,
            'params': params,
            'execution_time_ms': execution_time,
            'user_id': user_id,
            'success': success
        }
        
        if success:
            self.logger.info(f"Query executed: {json.dumps(log_data, ensure_ascii=False)}")
        else:
            self.logger.error(f"Query failed: {json.dumps(log_data, ensure_ascii=False)}")

class ApplicationLogger:
    """Application logger"""
    
    def __init__(self):
        self.logger = logging.getLogger('application')
        self.logger.setLevel(logging.INFO)
        
        # Create log directory
        log_dir = 'logs'
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        
        # File handler
        file_handler = logging.handlers.TimedRotatingFileHandler(
            filename=os.path.join(log_dir, 'application.log'),
            when='midnight',
            interval=1,
            backupCount=30,
            encoding='utf-8'
        )
        
        # Console handler
        console_handler = logging.StreamHandler()
        
        # Set format
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # Add handlers
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
    
    def log_user_action(self, action, user_id=None, details=None):
        """Log user action"""
        log_data = {
            'timestamp': datetime.now().isoformat(),
            'action': action,
            'user_id': user_id,
            'details': details
        }
        self.logger.info(f"User action: {json.dumps(log_data, ensure_ascii=False)}")
    
    def log_api_request(self, method, endpoint, user_id=None, status_code=None, response_time=None):
        """Log API request"""
        log_data = {
            'timestamp': datetime.now().isoformat(),
            'method': method,
            'endpoint': endpoint,
            'user_id': user_id,
            'status_code': status_code,
            'response_time_ms': response_time
        }
        self.logger.info(f"API request: {json.dumps(log_data, ensure_ascii=False)}")
    
    def log_error(self, error_type, error_message, user_id=None, details=None):
        """Log error"""
        log_data = {
            'timestamp': datetime.now().isoformat(),
            'error_type': error_type,
            'error_message': error_message,
            'user_id': user_id,
            'details': details
        }
        self.logger.error(f"Error occurred: {json.dumps(log_data, ensure_ascii=False)}")

# Global logger instances
db_logger = DatabaseQueryLogger()
app_logger = ApplicationLogger()
